<template>
  <div class="combined-detection">
    <div class="header">
      <h1>🚗 车辆与车牌综合识别</h1>
      <p class="subtitle">先检测车辆位置，再识别车牌信息</p>
      <router-link to="/" class="back-btn">← 返回首页</router-link>
    </div>

    <FileUpload @file-selected="handleFileSelected" />

    <ProgressBar v-if="isProcessing" :progress="progress" />

    <div v-if="results" class="results-container">
      <!-- 车辆检测结果 -->
      <div class="result-section">
        <h2 class="section-title">🚘 车辆检测结果</h2>
        <div class="stats-cards">
          <div class="stat-card">
            <div class="stat-number">{{ vehicleResult.total_vehicles || 0 }}</div>
            <div class="stat-label">检测到的车辆数量</div>
          </div>
        </div>

        <div class="results-table">
          <table>
            <thead>
            <tr>
              <th>车辆ID</th>
              <th>位置</th>
              <th>置信度</th>
              <th>尺寸</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(vehicle, index) in vehicleResult.results" :key="index">
              <td>#{{ index + 1 }}</td>
              <td>({{ vehicle.bbox[0] }}, {{ vehicle.bbox[1] }}) - ({{ vehicle.bbox[2] }}, {{ vehicle.bbox[3] }})</td>
              <td>{{ Math.round(vehicle.confidence * 100) }}%</td>
              <td>{{ vehicle.width }} × {{ vehicle.height }} px</td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 车牌识别结果 -->
      <div v-if="plateResult" class="result-section">
        <h2 class="section-title">🔢 车牌识别结果</h2>
        <div class="stats-cards">
          <div class="stat-card">
            <div class="stat-number">{{ plateResult.total_plates || 0 }}</div>
            <div class="stat-label">检测到的车牌数量</div>
          </div>
          <div class="stat-card">
            <div class="stat-number">{{ Math.round(averageConfidence * 100) }}%</div>
            <div class="stat-label">平均置信度</div>
          </div>
        </div>

        <div class="plates-list">
          <div
              v-for="(plate, index) in plateResult.results"
              :key="index"
              class="plate-card"
          >
            <div class="plate-header">
              <span class="plate-number">{{ plate.plate_number }}</span>
              <span class="plate-type">{{ plate.plate_type }}</span>
            </div>
            <div class="plate-details">
              <div class="detail-item">
                <span class="detail-label">车牌颜色:</span>
                <span class="detail-value">{{ plate.plate_color }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">检测置信度:</span>
                <span class="detail-value">{{ Math.round(plate.confidence * 100) }}%</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">位置:</span>
                <span class="detail-value">
                  ({{ plate.bbox[0] }}, {{ plate.bbox[1] }}) - ({{ plate.bbox[2] }}, {{ plate.bbox[3] }})
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 结果图片 -->
      <div class="result-image-section">
        <h3 class="subsection-title">📸 综合识别结果</h3>
        <div class="image-container">
          <img
              v-if="finalResultImageUrl"
              :src="finalResultImageUrl"
              alt="综合识别结果"
              class="result-image"
          >
        </div>
      </div>
    </div>

    <div class="api-status">
      <span class="status-item">
        <span class="status-dot" :class="{ 'online': isVehicleApiOnline }"></span>
        车辆API: {{ isVehicleApiOnline ? '在线' : '离线' }}
      </span>
      <span class="status-item">
        <span class="status-dot" :class="{ 'online': isPlateApiOnline }"></span>
        车牌API: {{ isPlateApiOnline ? '在线' : '离线' }}
      </span>
    </div>
  </div>
</template>

<script>
import FileUpload from '@/components/FileUpload.vue'
import ProgressBar from '@/components/ProgressBar.vue'
import { VehicleDetectionApi, PlateRecognitionApi } from '@/services/api'
import { validateImageFile } from '@/utils/helpers'

export default {
  components: {
    FileUpload,
    ProgressBar
  },
  data() {
    return {
      selectedFile: null,
      isProcessing: false,
      progress: 0,
      vehicleResult: null,
      plateResult: null,
      finalResultImageUrl: null,
      isVehicleApiOnline: false,
      isPlateApiOnline: false,
      error: null
    }
  },
  computed: {
    results() {
      return this.vehicleResult || this.plateResult
    },
    averageConfidence() {
      if (!this.plateResult || !this.plateResult.results?.length) return 0
      const total = this.plateResult.results.reduce((sum, item) => sum + item.confidence, 0)
      return total / this.plateResult.results.length
    }
  },
  methods: {
    handleFileSelected(file) {
      const validation = validateImageFile(file)
      if (!validation.valid) {
        this.error = validation.error || '文件无效'
        return
      }

      this.selectedFile = file
      this.error = null
      this.processFile()
    },

    async processFile() {
      if (!this.selectedFile) return

      this.isProcessing = true
      this.progress = 0
      this.vehicleResult = null
      this.plateResult = null
      this.finalResultImageUrl = null
      this.error = null

      try {
        // 第一步：车辆检测
        this.progress = 30;
        const vehicleResponse = await VehicleDetectionApi.detectVehicle(this.selectedFile);
        this.vehicleResult = vehicleResponse;

        // 第二步：使用车辆检测结果图片进行车牌识别
        this.progress = 60;

        // 获取车辆检测结果图片 - 检查格式
        let vehicleImageBase64 = vehicleResponse.result_image_base64;

        // 如果已经是数据URL格式，直接使用
        if (vehicleImageBase64.startsWith('data:image')) {
          // 直接使用数据URL创建图片元素
          this.finalResultImageUrl = vehicleImageBase64;

          // 提取纯base64部分用于车牌识别
          const base64Data = vehicleImageBase64.split(',')[1];

          // 将base64转换为Blob
          const blob = this.base64ToBlob(base64Data);
          const annotatedImageFile = new File([blob], 'annotated_vehicle.jpg', {
            type: 'image/jpeg'
          });

          // 使用标注后的图片进行车牌识别
          const plateResponse = await PlateRecognitionApi.recognizePlate(annotatedImageFile);
          this.plateResult = plateResponse;

          // 使用车牌识别结果作为最终展示图片
          if (plateResponse.result_image_base64) {
            this.finalResultImageUrl = `data:image/png;base64,${plateResponse.result_image_base64}`;
          }
        }
        // 如果是纯base64字符串
        else {
          // 创建数据URL用于预览
          this.finalResultImageUrl = `data:image/png;base64,${vehicleImageBase64}`;

          // 将base64转换为Blob
          const blob = this.base64ToBlob(vehicleImageBase64);
          const annotatedImageFile = new File([blob], 'annotated_vehicle.jpg', {
            type: 'image/jpeg'
          });

          // 使用标注后的图片进行车牌识别
          const plateResponse = await PlateRecognitionApi.recognizePlate(annotatedImageFile);
          this.plateResult = plateResponse;

          // 更新最终图片（如果车牌识别有更好的结果）
          if (plateResponse.result_image_base64) {
            this.finalResultImageUrl = `data:image/png;base64,${plateResponse.result_image_base64}`;
          }
        }

        this.progress = 100;

      } catch (err) {
        console.error('处理失败:', err)
        this.error = err.message || '处理过程中发生错误'
      } finally {
        this.isProcessing = false
      }
    },

// 修改 base64ToBlob 方法 - 处理纯base64字符串
    base64ToBlob(base64Data) {
      try {
        const byteString = atob(base64Data);
        const mimeType = 'image/jpeg'; // 默认设为JPEG

        const ab = new ArrayBuffer(byteString.length);
        const ia = new Uint8Array(ab);

        for (let i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
        }

        return new Blob([ab], { type: mimeType });
      } catch (error) {
        console.error('Base64转换错误:', error);
        throw new Error('图片数据格式不正确');
      }
    },

    // 辅助函数：将base64转换为Blob
    dataURItoBlob(dataURI) {
      const byteString = atob(dataURI.split(',')[1])
      const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
      const ab = new ArrayBuffer(byteString.length)
      const ia = new Uint8Array(ab)

      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }

      return new Blob([ab], { type: mimeString })
    },

    async checkApiHealth() {
      try {
        await VehicleDetectionApi.healthCheck()
        this.isVehicleApiOnline = true
      } catch {
        this.isVehicleApiOnline = false
      }

      try {
        await PlateRecognitionApi.healthCheck()
        this.isPlateApiOnline = true
      } catch {
        this.isPlateApiOnline = false
      }
    }
  },
  mounted() {
    this.checkApiHealth()
    setInterval(this.checkApiHealth, 30000)
  }
}
</script>

<style scoped>
.combined-detection {
  max-width: 100vw;
  margin: 0 auto;

  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 40px;
  position: relative;
}

.header h1 {
  font-size: 2.2rem;
  color: #2c3e50;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1.1rem;
  color: #7f8c8d;
  margin-bottom: 20px;
}

.back-btn {
  position: fixed;
  top: 10px;
  left: 0;
  color: #3498db;
  text-decoration: none;
  font-weight: 500;
}

.back-btn:hover {
  text-decoration: underline;
}

.results-container {
  margin-top: 40px;
}

.result-section {
  margin-bottom: 50px;
  gap: 20px;
  display:grid;
}

.section-title {
  color: #2c3e50;
  font-size: 1.8rem;
  margin: 0 0 30px 0;
  font-weight: 700;
}

.api-status {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-top: 40px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.9rem;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #dc3545;
}

.status-dot.online {
  background: #28a745;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .api-status {
    flex-direction: column;
    gap: 10px;
    align-items: center;
  }
}
</style>